package com.example.blog.modules.user.entity;

import com.example.blog.common.base.BaseEntity;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

@Entity
@Table(name = "users")
@Getter
@Setter
public class User extends BaseEntity implements UserDetails {
    
    @Column(nullable = false, unique = true, length = 50)
    private String username;
    
    @Column(nullable = false)
    private String password;
    
    @Column(nullable = false, unique = true, length = 100)
    private String email;
    
    @Column(length = 100)
    private String nickname;
    
    @Column(length = 500)
    private String avatar;
    
    @Column(length = 500)
    private String bio;
    
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "user_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    private Set<Role> roleSet = new HashSet<>();
    
    @Transient
    private Set<String> roles = new HashSet<>();
    
    private boolean enabled = true;
    
    private boolean emailVerified = false;
    
    @Column(length = 100)
    private String verificationToken;
    
    @Column
    private Long lastLoginTime;
    
    private String providerId;
    private String provider;
    
    @PostLoad
    private void onLoad() {
        roles = roleSet.stream()
                .map(Role::getName)
                .collect(Collectors.toSet());
    }
    
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        
        // 添加角色
        roleSet.forEach(role -> {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName().toUpperCase()));
            // 添加权限
            role.getPermissions().forEach(permission ->
                authorities.add(new SimpleGrantedAuthority(permission.toUpperCase()))
            );
        });
        
        return authorities;
    }
    
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    
    @Override
    public boolean isEnabled() {
        return enabled;
    }
} 